{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 152,
   "id": "8dc02932",
   "metadata": {},
   "outputs": [],
   "source": [
    "#pip install PdfReader"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b50bdff",
   "metadata": {},
   "source": [
    "## Convert PDF to Text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "id": "5e4f1f7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import PyPDF2\n",
    "\n",
    "def extract_text_from_pdf(pdf_file_path):\n",
    "    with open(pdf_file_path, 'rb') as file:\n",
    "        reader = PyPDF2.PdfReader(file)\n",
    "        num_pages = len(reader.pages)\n",
    "\n",
    "        combined_text = \"\"\n",
    "        for page_number in range(num_pages):\n",
    "            page = reader.pages[page_number]\n",
    "            text = page.extract_text()\n",
    "            combined_text += text\n",
    "\n",
    "        return combined_text\n",
    "\n",
    "# Usage example\n",
    "pdf_path = '1_55661.pdf'\n",
    "\n",
    "# context = extract_text_from_pdf(pdf_path)[3268:7000]\n",
    "# print(context)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "583bc97d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def separate_paragraphs(text):\n",
    "    paragraphs = text.split(\"  \\n\")  # Split text by double line breaks\n",
    "\n",
    "    # Remove leading and trailing whitespaces from each paragraph\n",
    "    paragraphs = [paragraph.strip() for paragraph in paragraphs]\n",
    "\n",
    "    return paragraphs\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8678e5f2",
   "metadata": {},
   "source": [
    "### Count total paragraph from PDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "93f6fa91",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "283"
      ]
     },
     "execution_count": 137,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "full_doc = extract_text_from_pdf(pdf_path)\n",
    "full_paras = separate_paragraphs(full_doc)\n",
    "len(full_paras)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "1908f943",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"what are the supported platform for ssh runner?\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fa3bcef",
   "metadata": {},
   "source": [
    "### Retrieve the Context from Text "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "id": "20584c80",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Most Relevant context: First, download the gitlab-runner distribution for the appropriate platform at \n",
      "https://docs.gitlab.com/runner/install/ . In this configura tion, the SSH GitLab runner is installed on a Linux \n",
      "x86 Red Hat distribution, but similar installation and configuration can be performed on other supported \n",
      "platforms.\n",
      "\n",
      "The SSH runners are executed on a supported platform (Windows, Linux or MacOS) and connect to a \n",
      "target machine through SSH for the pipeline execution. In that configuration, SSH runners act like \n",
      "gateways to connect platforms: the GitLab server will send the pipeline actions to the SSH runner which \n",
      "will forward them to the target machine, in this case th e z/OS environment. The different stages of the \n",
      "pipeline will be executed on the target z/OS machine and results will be sent back to the GitLab server \n",
      "through the same mechanism.\n",
      "\n",
      "Provide the GitLab server URL and the registration token to register the runner. Then provide a description \n",
      "for this runner and leave empty when prompted for tags  (tags can be modified later if necessary) . Provide \n",
      "the type of executor by typing ssh and provide the nec essary information for SSH communication (IP or \n",
      "hostname of the target z/OS machine, port, username and password or path to the SSH identity file). \n",
      "When finished, start the runner by issuing the sudo g itlab-runner start  command.\n",
      "\n",
      "Similar pipeline definitions are configured for the EPSM project and for the zAppBuild project.\n",
      "\n",
      "In Linux, install the downloaded package with the command rpm -i gitlab-runner_amd64.rpm . \n",
      "Then register the runner to the GitLab server, by issuing the sudo  gitlab-runner register  command. The \n",
      "configurator prompts for several pieces of information that are displayed in the GitLab server \n",
      "Administration area (Runners section):\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1789"
      ]
     },
     "execution_count": 187,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "\n",
    "def find_most_similar_text(sentence, text_objects):\n",
    "    # Create a TF-IDF vectorizer\n",
    "    vectorizer = TfidfVectorizer()\n",
    "\n",
    "    # Fit the vectorizer on text_objects\n",
    "    tfidf_matrix = vectorizer.fit_transform(text_objects)\n",
    "\n",
    "    # Transform the input sentence using the fitted vectorizer\n",
    "    sentence_vector = vectorizer.transform([sentence])\n",
    "\n",
    "    # Calculate cosine similarities between the sentence vector and all text objects\n",
    "    similarities = cosine_similarity(sentence_vector, tfidf_matrix)\n",
    "\n",
    "    # Find the index of the most similar text object\n",
    "    most_similar_index = similarities.argmax()\n",
    "\n",
    "    # Get the most similar text object\n",
    "    most_similar_text = text_objects[most_similar_index]\n",
    "\n",
    "    # Check the length of the most similar text object\n",
    "    if len(most_similar_text) < 2000:\n",
    "        # Find the indices and similarities of the related text objects\n",
    "        sorted_indices = similarities.argsort()[0][::-1]\n",
    "        sorted_similarities = similarities[0, sorted_indices]\n",
    "\n",
    "        # Iterate over the related text objects and add paragraphs until length exceeds 2000 characters\n",
    "        for idx, similarity in zip(sorted_indices, sorted_similarities):\n",
    "            if idx != most_similar_index:\n",
    "                related_text = text_objects[idx]\n",
    "                if len(most_similar_text) + len(related_text) + 2 > 2000:  # +2 for \"\\n\\n\"\n",
    "                    break\n",
    "                most_similar_text += \"\\n\\n\" + related_text\n",
    "\n",
    "    return most_similar_text\n",
    "question = \"what are the supported platform for ssh runner?\"\n",
    "\n",
    "most_relevant_text = find_most_similar_text(question, ful_paras)\n",
    "print(\"Most Relevant context:\", most_relevant_text)\n",
    "len(most_relevant_text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88d25bba",
   "metadata": {},
   "source": [
    "### Run LLM model on most_relevant_text "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "4d754069",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INPUT PROMPT:  Answer the question based on the context below. Context: First, download the gitlab-runner distribution for the appropriate platform at \n",
      "https://docs.gitlab.com/runner/install/ . In this configura tion, the SSH GitLab runner is installed on a Linux \n",
      "x86 Red Hat distribution, but similar installation and configuration can be performed on other supported \n",
      "platforms.\n",
      "\n",
      "The SSH runners are executed on a supported platform (Windows, Linux or MacOS) and connect to a \n",
      "target machine through SSH for the pipeline execution. In that configuration, SSH runners act like \n",
      "gateways to connect platforms: the GitLab server will send the pipeline actions to the SSH runner which \n",
      "will forward them to the target machine, in this case th e z/OS environment. The different stages of the \n",
      "pipeline will be executed on the target z/OS machine and results will be sent back to the GitLab server \n",
      "through the same mechanism.\n",
      "\n",
      "Provide the GitLab server URL and the registration token to register the runner. Then provide a description \n",
      "for this runner and leave empty when prompted for tags  (tags can be modified later if necessary) . Provide \n",
      "the type of executor by typing ssh and provide the nec essary information for SSH communication (IP or \n",
      "hostname of the target z/OS machine, port, username and password or path to the SSH identity file). \n",
      "When finished, start the runner by issuing the sudo g itlab-runner start  command.\n",
      "\n",
      "Similar pipeline definitions are configured for the EPSM project and for the zAppBuild project.\n",
      "\n",
      "In Linux, install the downloaded package with the command rpm -i gitlab-runner_amd64.rpm . \n",
      "Then register the runner to the GitLab server, by issuing the sudo  gitlab-runner register  command. The \n",
      "configurator prompts for several pieces of information that are displayed in the GitLab server \n",
      "Administration area (Runners section): Question: what are the supported platform for ssh runner?\n",
      "BAM OUTPUT:  {'model_id': 'bigscience/bloom', 'created_at': '2023-06-21T05:24:53.191Z', 'results': [{'generated_text': ' \\nAnswer: Linux, Windows, MacOS Question', 'generated_token_count': 10, 'input_token_count': 397, 'stop_reason': 'STOP_SEQUENCE', 'seed': 2059693411}]}\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import time\n",
    "from textwrap import dedent\n",
    "from PIL import Image\n",
    "import json\n",
    "import re\n",
    "import pandas as pd\n",
    "from ibm_watson import DiscoveryV2\n",
    "from ibm_cloud_sdk_core.authenticators import IAMAuthenticator\n",
    "from nltk.translate import meteor_score as ms\n",
    "from rouge_score import rouge_scorer\n",
    "from bs4 import BeautifulSoup\n",
    "import requests\n",
    "from nltk.translate import bleu_score\n",
    "import nltk\n",
    "import torch\n",
    "import gc\n",
    "\n",
    "\n",
    "#bamToken = 'Bam-key'\n",
    "\n",
    "\n",
    "# question  = \"What is the purpose of the provided extracts and how can they be integrated into a pipeline for z/OS-related capabilities?\"\n",
    "\n",
    "question = \"what are the supported platform for ssh runner?\"\n",
    "\n",
    "chat_history = f\"Answer the question based on the context below. \" + \\\n",
    "    \"Context: \"  + most_relevant_text + \\\n",
    "    \" Question: \" + question\n",
    "\n",
    "model_input = chat_history.replace(\"<split>\", \"\\n\")\n",
    "\n",
    "print(\"INPUT PROMPT: \", model_input)\n",
    "\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Authorization': bamToken,\n",
    "}\n",
    "\n",
    "json_data = {\n",
    "    'model_id': 'bigscience/bloom',\n",
    "    # 'model_id': 'google/flan-ul2',\n",
    "#     'model_id': 'google/flan-t5-xxl',\n",
    "    # 'model_id': 'ibm/coga-3b-0.1',\n",
    "    # 'model_id':'flan-t5-xl-mpt-2zfTOrpU-2023-05-01-19-48-20',\n",
    "    \n",
    "    'inputs':  [model_input],\n",
    "\n",
    "        #bam\n",
    "        'parameters': {\n",
    "        # \"stream\": \"true\",\n",
    "        'temperature': 0.3,\n",
    "        'min_new_tokens': 10,\n",
    "        'max_new_tokens': 200,\n",
    "        'stop_sequences': ['Question']\n",
    "\n",
    "         # Modify this parameter to reduce the batch size\n",
    "        # 'decoding_method': 'greedy'\n",
    "        # 'repetition_penalty': 1.0,\n",
    "    },\n",
    "}\n",
    "\n",
    "#bam\n",
    "# response = requests.post('https://bam-api.res.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "#Coga\n",
    "response = requests.post('https://fmaas-dev-api.bx.cloud9.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "\n",
    "json_response = json.loads(response.content.decode(\"utf-8\"))\n",
    "print(\"BAM OUTPUT: \", json_response)\n",
    "\n",
    "model_output1 = json_response['results'][0]['generated_text']\n",
    "model_output1 = model_output1.replace(\"Question\", '')\n",
    "model_output1 = model_output1.replace(\"Answer: \", '')\n",
    "\n",
    "# Seprate sentences\n",
    "sentences = model_output1.split(\". \")\n",
    "# remove duplicates SENTENCES\n",
    "unique_sentences = list( dict.fromkeys(sentences))\n",
    "\n",
    "if not model_output1.endswith(\".\"):\n",
    "# remove the last sentence if not . at last\n",
    "    unique_sentences.pop()\n",
    "\n",
    "# join unique sentences back into a text \n",
    "model_output = \". \".join(unique_sentences)+ \".\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "id": "4a8492b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FINAL ANSWER:   \n",
      "Linux, Windows, MacOS \n"
     ]
    }
   ],
   "source": [
    "print(\"FINAL ANSWER: \", model_output1)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c478de62",
   "metadata": {},
   "source": [
    "## Example Questions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "bb5644a4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INPUT PROMPT:  Answer the question based on the context below. Context: As the execution of the pipeline is performed through an SSH channel, it is important to have the Bash \n",
      "shell available f or the user who will execute the build actions. More importantly, the Bash shell must be \n",
      "set to be the first program executed by the user when logging into z/OS Unix System Services. This \n",
      "parameter is controlled through the PROGRAM keyword in the RACF’s us er definition, as part of the OMVS \n",
      "segment. To change the PROGRAM value for an existing user, please customize and use the following \n",
      "RACF ALTUSER command:\n",
      "\n",
      "At the end of the job execution, the developer can open the Wazi Analyze UI, with the link provided in the \n",
      "output log of the job. Through this web -based  solution, analysis can be performed with the latest versions \n",
      "of the artifacts that were used during the build, ensuring consistency between the structure of the \n",
      "application and the actual load modules that were built.\n",
      "\n",
      "Using the multi -project pipelines feature, it is possible to trigger the execution of the external projects \n",
      "pipeline, which solves this complex situation. To be cloned on z/OS USS, the pipelines for t he EPSM \n",
      "project, the Common project and the zAppBuild project will just contain a dummy operation, as cloning is \n",
      "automatically generated by the GitLab server in the execution of the pipeline. The pipeline definition for \n",
      "the Common project is as follows:\n",
      "\n",
      "In the GitLab CI /CD section of the EPSC project, the correct execution of the pipeline can be checked: Question: the execution of the pipeline is performed through which channel?\n",
      "BAM OUTPUT:  {'model_id': 'bigscience/bloom', 'created_at': '2023-06-21T05:33:01.741Z', 'results': [{'generated_text': ' Answer: SSH channel. Question: it is important to have the Bash shell available for the user who will execute the build actions. Answer: Yes. Question', 'generated_token_count': 31, 'input_token_count': 340, 'stop_reason': 'STOP_SEQUENCE', 'seed': 4071738245}]}\n"
     ]
    }
   ],
   "source": [
    "question = \"the execution of the pipeline is performed through which channel?\"\n",
    "\n",
    "most_relevant_text = find_most_similar_text(question, ful_paras)\n",
    "\n",
    "chat_history = f\"Answer the question based on the context below. \" + \\\n",
    "    \"Context: \"  + most_relevant_text + \\\n",
    "    \" Question: \" + question\n",
    "\n",
    "model_input = chat_history.replace(\"<split>\", \"\\n\")\n",
    "\n",
    "print(\"INPUT PROMPT: \", model_input)\n",
    "\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Authorization': bamToken,\n",
    "}\n",
    "\n",
    "json_data = {\n",
    "    'model_id': 'bigscience/bloom',\n",
    "\n",
    "    'inputs':  [model_input],\n",
    "\n",
    "        #bam\n",
    "        'parameters': {\n",
    "        # \"stream\": \"true\",\n",
    "        'temperature': 0.3,\n",
    "        'min_new_tokens': 10,\n",
    "        'max_new_tokens': 200,\n",
    "        'stop_sequences': ['Question']\n",
    "    },\n",
    "}\n",
    "\n",
    "#bam\n",
    "# response = requests.post('https://bam-api.res.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "#Coga\n",
    "response = requests.post('https://fmaas-dev-api.bx.cloud9.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "\n",
    "json_response = json.loads(response.content.decode(\"utf-8\"))\n",
    "print(\"BAM OUTPUT: \", json_response)\n",
    "\n",
    "model_output1 = json_response['results'][0]['generated_text']\n",
    "model_output1 = model_output1.replace(\"Question\", '')\n",
    "model_output1 = model_output1.replace(\"Answer: \", '')\n",
    "\n",
    "# Seprate sentences\n",
    "sentences = model_output1.split(\". \")\n",
    "# remove duplicates SENTENCES\n",
    "unique_sentences = list( dict.fromkeys(sentences))\n",
    "\n",
    "if not model_output1.endswith(\".\"):\n",
    "# remove the last sentence if not . at last\n",
    "    unique_sentences.pop()\n",
    "\n",
    "# join unique sentences back into a text \n",
    "model_output = \". \".join(unique_sentences)+ \".\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 168,
   "id": "f65b37cf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FINAL ANSWER:   SSH channel. : it is important to have the Bash shell available for the user who will execute the build actions. Yes. \n"
     ]
    }
   ],
   "source": [
    "print(\"FINAL ANSWER: \", model_output1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "14078b0b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INPUT PROMPT:  Answer the question based on the context below. Context: As the execution of the pipeline is performed through an SSH channel, it is important to have the Bash \n",
      "shell available f or the user who will execute the build actions. More importantly, the Bash shell must be \n",
      "set to be the first program executed by the user when logging into z/OS Unix System Services. This \n",
      "parameter is controlled through the PROGRAM keyword in the RACF’s us er definition, as part of the OMVS \n",
      "segment. To change the PROGRAM value for an existing user, please customize and use the following \n",
      "RACF ALTUSER command:\n",
      "\n",
      "At the end of the job execution, the developer can open the Wazi Analyze UI, with the link provided in the \n",
      "output log of the job. Through this web -based  solution, analysis can be performed with the latest versions \n",
      "of the artifacts that were used during the build, ensuring consistency between the structure of the \n",
      "application and the actual load modules that were built.\n",
      "\n",
      "Using the multi -project pipelines feature, it is possible to trigger the execution of the external projects \n",
      "pipeline, which solves this complex situation. To be cloned on z/OS USS, the pipelines for t he EPSM \n",
      "project, the Common project and the zAppBuild project will just contain a dummy operation, as cloning is \n",
      "automatically generated by the GitLab server in the execution of the pipeline. The pipeline definition for \n",
      "the Common project is as follows:\n",
      "\n",
      "In the GitLab CI /CD section of the EPSC project, the correct execution of the pipeline can be checked: Question: the execution of the pipeline is performed through which channel?\n",
      "BAM OUTPUT:  {'model_id': 'bigscience/bloom', 'created_at': '2023-06-21T06:29:37.216Z', 'results': [{'generated_text': ' Answer: SSH channel. Question: what is the importance of having the Bash shell available for the user who will execute the build actions? Answer: the user who will execute the build actions must have the Bash shell available. Question', 'generated_token_count': 45, 'input_token_count': 340, 'stop_reason': 'STOP_SEQUENCE', 'seed': 3686780085}]}\n",
      "FINAL ANSWER:   SSH channel. : what is the importance of having the Bash shell available for the user who will execute the build actions? the user who will execute the build actions must have the Bash shell available. \n"
     ]
    }
   ],
   "source": [
    "question = \"the execution of the pipeline is performed through which channel?\"\n",
    "\n",
    "most_relevant_text = find_most_similar_text(question, ful_paras)\n",
    "\n",
    "chat_history = f\"Answer the question based on the context below. \" + \\\n",
    "    \"Context: \"  + most_relevant_text + \\\n",
    "    \" Question: \" + question\n",
    "\n",
    "model_input = chat_history.replace(\"<split>\", \"\\n\")\n",
    "\n",
    "print(\"INPUT PROMPT: \", model_input)\n",
    "\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Authorization': bamToken,\n",
    "}\n",
    "\n",
    "json_data = {\n",
    "    'model_id': 'bigscience/bloom',    \n",
    "    'inputs':  [model_input],\n",
    "\n",
    "        #bam\n",
    "        'parameters': {\n",
    "        # \"stream\": \"true\",\n",
    "        'temperature': 0.3,\n",
    "        'min_new_tokens': 10,\n",
    "        'max_new_tokens': 200,\n",
    "        'stop_sequences': ['Question']\n",
    "    },\n",
    "}\n",
    "\n",
    "#bam\n",
    "# response = requests.post('https://bam-api.res.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "#Coga\n",
    "response = requests.post('https://fmaas-dev-api.bx.cloud9.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "\n",
    "json_response = json.loads(response.content.decode(\"utf-8\"))\n",
    "print(\"BAM OUTPUT: \", json_response)\n",
    "\n",
    "model_output1 = json_response['results'][0]['generated_text']\n",
    "model_output1 = model_output1.replace(\"Question\", '')\n",
    "model_output1 = model_output1.replace(\"Answer: \", '')\n",
    "\n",
    "# Seprate sentences\n",
    "sentences = model_output1.split(\". \")\n",
    "# remove duplicates SENTENCES\n",
    "unique_sentences = list( dict.fromkeys(sentences))\n",
    "\n",
    "if not model_output1.endswith(\".\"):\n",
    "# remove the last sentence if not . at last\n",
    "    unique_sentences.pop()\n",
    "\n",
    "# join unique sentences back into a text \n",
    "model_output = \". \".join(unique_sentences)+ \".\"\n",
    "\n",
    "print(\"FINAL ANSWER: \", model_output1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "id": "919ef4d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INPUT PROMPT:  Answer the question based on the context below. Context: To change this default behavior of checking Git for every job, specific variables can be set either at the \n",
      "pipeline level or at the job level. The latter option is the preferred way for fine -tuning and manage the \n",
      "repository checkout granularly.  The GIT_ST RATEGY12 variable controls how the GitLab CI/CD pipeline \n",
      "performs the Git checkout: when set to clone , the entire repository will be cloned for this job; when set \n",
      "to fetch , only the changes in the Git repository of the project are retrieved. Whe n set to none , no Git \n",
      "operation is performed, and the project’s workspace is left untouched.\n",
      "\n",
      "Integrating IBM z/OS platform in CI/CD pipelines with GitLab   Page 7/22 3 Setting up an initial pipeline with  GitLab CI /CD \n",
      "Once the GitLab SSH runner is set up for z/OS, CI /CD pipelines can be executed on Mainframe. The \n",
      "definition of pipelines in GitLab CI are done throug h a configuration file, called .gitlab-ci.yml  and stored \n",
      "be default at the root level of the project’s repository  (it can be changed in the project’s CI/CD \n",
      "configuration) . GitLab provides a complete documentation about keyworks that can be used in pipeline\n",
      "\n",
      "CI_DEBUG_TRACE:  \"true\" \n",
      "For convenience, the extended trace has been activated to facilitate debugging, but it is recommended to \n",
      "remove it when the pipeline performs the desired actions correctly.  Please n ote the use of GitLab CI/CD \n",
      "variables which are available in the pipeline definition: in this case, the $CI_PROJECT_DIR  variable  contains \n",
      "the path where the project is checked out on the target machine, and the $CI_PIPELINE_ID  variable \n",
      "contains the unique number associated with the pipeline execution. These variables are defined in the \n",
      "GitLab CI/CD documentation8. \n",
      "In the GitLab CI /CD section of this project, the execution of this pipeline was manually triggered and \n",
      "finished successfully in 2 8 seconds:\n",
      "\n",
      "Integrating IBM z/OS platform \n",
      "in CI/CD pipelines with GitLab\n",
      "\n",
      "5.1.2 Integratin g Code Review into the GitLab CI/CD pipeline Question: Which variable controls GitLab CI/CD Git checkout?\n",
      "BAM OUTPUT:  {'model_id': 'bigscience/bloom', 'created_at': '2023-06-21T09:56:18.612Z', 'results': [{'generated_text': ' Answer: GIT_ST RATEGY12 \\nQuestion', 'generated_token_count': 11, 'input_token_count': 480, 'stop_reason': 'STOP_SEQUENCE', 'seed': 1168129335}]}\n",
      "FINAL ANSWER:   GIT_ST RATEGY12 \n",
      "\n"
     ]
    }
   ],
   "source": [
    "question = \"Which variable controls GitLab CI/CD Git checkout?\"\n",
    "\n",
    "most_relevant_text = find_most_similar_text(question, ful_paras)\n",
    "\n",
    "chat_history = f\"Answer the question based on the context below. \" + \\\n",
    "    \"Context: \"  + most_relevant_text + \\\n",
    "    \" Question: \" + question\n",
    "\n",
    "model_input = chat_history.replace(\"<split>\", \"\\n\")\n",
    "\n",
    "print(\"INPUT PROMPT: \", model_input)\n",
    "\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Authorization': bamToken,\n",
    "}\n",
    "\n",
    "json_data = {\n",
    "    'model_id': 'bigscience/bloom',\n",
    "    'inputs':  [model_input],\n",
    "        'parameters': {\n",
    "        # \"stream\": \"true\",\n",
    "        'temperature': 0.3,\n",
    "        'min_new_tokens': 10,\n",
    "        'max_new_tokens': 200,\n",
    "        'stop_sequences': ['Question']\n",
    "    },\n",
    "}\n",
    "\n",
    "#bam\n",
    "# response = requests.post('https://bam-api.res.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "#Coga\n",
    "response = requests.post('https://fmaas-dev-api.bx.cloud9.ibm.com/v1/generate', headers=headers, json=json_data)\n",
    "\n",
    "\n",
    "json_response = json.loads(response.content.decode(\"utf-8\"))\n",
    "print(\"BAM OUTPUT: \", json_response)\n",
    "\n",
    "model_output1 = json_response['results'][0]['generated_text']\n",
    "model_output1 = model_output1.replace(\"Question\", '')\n",
    "model_output1 = model_output1.replace(\"Answer: \", '')\n",
    "\n",
    "# Seprate sentences\n",
    "sentences = model_output1.split(\". \")\n",
    "# remove duplicates SENTENCES\n",
    "unique_sentences = list( dict.fromkeys(sentences))\n",
    "\n",
    "if not model_output1.endswith(\".\"):\n",
    "# remove the last sentence if not . at last\n",
    "    unique_sentences.pop()\n",
    "\n",
    "# join unique sentences back into a text \n",
    "model_output = \". \".join(unique_sentences)+ \".\"\n",
    "\n",
    "print(\"FINAL ANSWER: \", model_output1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a487addb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
